<template>
  <div class="login-container">
    <!-- 背景视频区域 -->
    <div class="v">
      <video
        class="f"
        id="bgvid"
        playsinline=""
        autoplay
        muted
        loop=""
        preload="auto"
      >
        <source src="../../assets/video/Cruising boat.mp4" type="video/mp4" />
      </video>
    </div>

    <!-- 表单输入区域 -->
    <el-form
      :model="loginFrom"
      status-icon
      :rules="rules"
      ref="loginFrom"
      label-width="100px"
      class="login-loginFrom"
    >
      <!-- 项目名称 -->
      <h1 class="h1">帆船运动俱乐部</h1>
      <!-- 角标区域 -->
      <div class="jiaobiao" @click="isErwei=!isErwei">
      <svg class="icon icon-jiao"  aria-hidden="true">
        <use :xlink:href="isErwei?'#icon-erweimajiaobiao1':'#icon-diannaojiaobiao'"></use>
      </svg>

      </div>
      <!-- 表单输入区域（登陆界面区域） -->
      <!-- 二维码登录区域 -->
      <div class="erweima" v-if="isErwei">
        <div class="imgBox">
        <img :src="qrimgrul" class="erweiing" alt="" />
        <b class="mask" v-show="isScancode"></b>

        </div>

        <p style="color: #fff; letter-spacing: 2px; font-size: 20px">
          请使用手机微信扫码登录
        </p>
      </div>

      <!-- 用户名区域  普通账号登录区域-->
      <div class="input" v-else>
        <el-form-item label="用户名" prop="username">
          <el-input
            type="text"
            v-model="loginFrom.username"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <!-- 密码区域 -->
        <!-- prop根据规则校验的属性 -->
        <el-form-item label="密码" prop="password">
          <el-input
            type="password"
            v-model="loginFrom.password"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <!-- 验证码区域 -->
        <!-- 原生事件需要加native才能生效 -->
        <el-form-item label="验证码" prop="captcha">
          <el-input
            type="text"
            class="captcha"
            v-model="loginFrom.captcha"
            @keydown.native.enter="submitForm('loginFrom')"
            autocomplete="off"
          >
          </el-input>
          <span
            class="captcha-svg"
            v-html="captcha"
            @click="refreshCaptcha"
          ></span>
        </el-form-item>

        <!-- 登录按钮区域 -->
        <el-form-item>
          <el-button type="primary" @click="submitForm('loginFrom')"
            >登录</el-button
          >
        </el-form-item>
      </div>
    </el-form>
  </div>
</template>

<script>
import { loginApi, getCaptchaApi, verifyCaptchaApi,getQrcodeUrlApi,wechatLoginApi } from "../../api";
import antiShake from "../../utils/antiShake"; //引入防抖函数
//引入socket.io
import io from "socket.io-client"
//引入qrcode
import qrcode from "qrcode"


//引入VUEX的辅助函数
import {mapMutations} from "vuex"
//用户登陆操作流程
//收集用户的用户名和密码发送给服务端
//服务端进行密码和用户名的校验，校验通过返回用户的信息个token
//将token存储到本地
//登陆成功跳转到主页
var validateUsn = (rule, value, callback) => {
  //用户名正则，3到16位（字母，数字，下划线，减号）
  var uPattern = /^[a-zA-Z0-9_-]{3,16}$/;
  if (uPattern.test(value)) {
    callback();
  } else {
    callback("3到16位（字母，数字，下划线，减号）");
  }
};
var validatecaphcha = (rule, value, callback) => {
  if (!value) {
    callback("验证码输入不能为空");
  } else {
    callback();
  }
};
var validatePsw = (rule, value, callback) => {
  if (!value) {
    callback("密码输入不能为空");
  } else {
    callback();
  }
};
export default {
  created() {
    //页面加载的时候就调用，让验证码显示出来
    // this.refreshCaptcha();
    getCaptchaApi().then((res) => {
      // console.log(123135);

      this.captcha = res.data.img;
    });
  },
  data() {
    return {
      loginFrom: {
        username: "",
        password: "",
        captcha: "",
      },
      isScancode:false, //控制显示遮罩
      isErwei: false, //控制是否使用二维码登录
      // isErwei: true, //控制是否使用二维码登录
      captcha: "",
      qrimgrul:"",
      rules: {
        //校验逻辑
        username: [{ validator: validateUsn, trigger: "blur" }],
        password: [{ validator: validatePsw, trigger: "blur" }],
        captcha: [{ validator: validatecaphcha, trigger: "blur" }],
      },
    };
  },
  methods: {
    ...mapMutations(["setUserInfo"]),
    //点击获取验证码
    refreshCaptcha() {
      antiShake(() => {
        //加入防抖功能
        getCaptchaApi().then((res) => {
          // console.log(123135);

          this.captcha = res.data.img;
        });
      }, 200);
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //登陆动画
          const loading = this.$loading({
            lock: true,
            text: "正在拼命加载",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.7)",
          });
          //解构表单中的数据
          let { captcha, username, password } = this.loginFrom;
          verifyCaptchaApi(captcha).then((res) => {
            if (res.data.state) {
              //验证通过 登陆主页   用户 密码登陆
              loginApi(username, password).then((res) => {
                // console.log(res);
                if (res.data.state) {
                  //登陆成功  将token存到本地  跳转到主页
                  loading.close(); //关闭登陆动画
                  localStorage.setItem("app-token", res.data.token);
                  //将用户信息存到vuex中
                  //将登陆信息存到本地localstorage中
                  localStorage.setItem("app-userInfo",JSON.stringify(res.data.userInfo) ) 
                  //不能直接存对象，需要用JSON.stringify转化一下

                  // console.log(res.data.userInfo);
                  this.setUserInfo(res.data.userInfo)

                   this.$router.push("/")
                 
                } else {
                  //登陆失败
                  loading.close(); //关闭登陆动画
                  this.$message.error("用户名或者密码错误");
                }
              });
            } else {
              //验证不通过
              this.$message.error("验证码输入不正确");
              this.refreshCaptcha();
              this.loginFrom.captcha = "";
              loading.close(); //关闭登陆动画
            }
          });

          // console.log(this.loginFrom);
          // alert("submit!");
        } else {
          // console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
  watch: {
    isErwei(newVal){
      // console.log(newVal);
      //判断用户是否切换到二维码登录  如果切换到二维码登录就要和socket.io建立链接
     if(newVal){
      //  console.log(io("ws://chst.vip");
      let socket =io("ws://chst.vip")
      socket.on('connect',()=>{
        // console.log("链接成功");
        getQrcodeUrlApi()
          .then(res=>{
            // console.log(res.data.scanCodeUrl);
            let qrUrl = res.data.scanCodeUrl //获取服务器返回的二维码地址 
            //将二维码地址生成二维码
            qrcode.toDataURL(qrUrl,(err,imgUrl)=>{
              if(err) throw err
              // console.log(imgUrl);
              this.qrimgrul=imgUrl
            } )
          })
      })
      //扫码成功事件
      socket.on("scancodeSuccess",(data)=>{
        // console.log(777);
        // console.log(data); //服务端socket返回的数据

        const loading = this.$loading({
            lock: true,
            text: "正在拼命加载",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.7)",
          });



        let {wechatCode} =data;
        this.isScancode=true;

        //微信登陆
        wechatLoginApi(wechatCode)
          .then(res=>{
            // this.$store.dispatch("FETCH_MENU_LIST")//测试用
            // console.log(res);
            //登录成功
            //将token存到本地
            localStorage.setItem("app-userInfo",JSON.stringify(res.data.userInfo) ) 
                  //不能直接存对象，需要用JSON.stringify转化一下
            localStorage.setItem("app-token",res.data.token)
            //将用户的信息页存到本地
            localStorage.setItem("userInfo",JSON.stringify(res.data.userInfo) ) //存登录信息
            //将用户的登陆信息存到本地local storage中
            // localStorage.setUserInfo()
           
            loading.close(); //关闭登陆动画

            //将userInfo存到vuex中
            this.setUserInfo(res.data.userInfo)

            //跳转到主页
            this.$router.push("/")

          })
      } )
     }
    }
  }
};
</script>
<style scoped lang="less">
.v {
  //首页动态背景图样式
  position: fixed;
  width: 100%;
  height: 100%;
  overflow: hidden;
  z-index: -10000;
  // background-color:skyblue;
  .f {
    position: absolute;
    top: 50%;
    left: 50%;
    min-width: 100%;
    min-height: 100%;
    width: auto;
    height: auto;
    z-index: -9999;
    -webkit-transform: translateX(-50%) translateY(-50%);
    transform: translateX(-50%) translateY(-50%);
    -webkit-transition: 1s opacity;
    transition: 1s opacity;
    // background-color:skyblue;
  }
  .v:before {
    content: "";
    position: absolute;
    width: 100%;
    height: 100%;
    display: block;
    z-index: -1000;
    top: 0;
    left: 0;
    // background: rgba(90,20,10,.2);  //滤镜
  }
}
//输入框区域
.login-loginFrom {
  text-align: center;
  border-radius: 10px;
  width: 400px;
  height: 485px;
  position: fixed;
  background: rgba(124, 158, 197, 0.3);
  right: 150px;
  bottom: 80px;
  box-sizing: border-box;
  & /deep/ .el-input__inner {
    //深度选择器
    width: 250px;
    height: 45px;
  }
  .jiaobiao{
     width: 60px;
    height: 60px;
    position: absolute;
    right: 3px;
    top: 3px;
    color: rgb(239, 243, 247) ;
    cursor: pointer; //让鼠标变成手的形式

  .icon-jiao{
    width: 100%;
    height: 100%;
    // border-radius: 20px;
  }
  }
  .imgBox  {
   position: relative;
    margin-top: 20px;
    width: 200px;
      height: 200px;

    .erweiing{
     width: 100%;
      height: 100%;
      position: absolute;

    }
    .mask{
      width: 100%;
      height: 100%;
       opacity: 0.8;
      background-color: #fff;
      position: absolute;
      background-image: url("../../assets/imgs/扫码成功.png") ;
      background-size: 80%;
      background-repeat: no-repeat;
      background-position: center;
    }
  }
  .input {
    margin-top: 80px;
  }
  & /deep/ .el-form-item {
    padding-right: 60px;
  }
  .h1 {
    margin-top: 80px;
    color: white;
    letter-spacing: 5px;
  }
  & /deep/ .el-form-item__label {
    color: white;
  }
  /deep/ .el-form-item__content {
    width: 250px !important;
  }

  .captcha {
    width: 100px;
    vertical-align: top;
    & /deep/ .el-input__inner {
      width: 100%;
      height: 45px;
      border-radius: 5px 0 0 5px;
      border: 0;
      font-size: 18px;
    }
  }
  .captcha-svg {
    background: #fff;
    display: inline-block;
    height: 45px;
    width: 150px;
    text-align: center;
    cursor: pointer;
    border: 0;
    border-radius: 0px 5px 5px 0;
  }
}
</style>